import { toJS } from "mobx";
import AppList from "./List";
import React, { Fragment } from "react";
import { SearchBar } from "weaver-mobile";
import { inject, observer } from "mobx-react";
import { withRouter } from 'react-router-dom';
import Loading from "../../../common/loading";
import If, { Then, Else } from "../../../common/if";

@inject('appListStore')
@withRouter
@observer
export default class AppListPage extends React.Component {
  constructor(props) {
    super();

    this.store = props.appListStore;
  }

  componentDidMount() {
    this.store.init();
  }

  getApps() {
    const { searchText, apps } = this.store;
    const text = searchText.toLowerCase();

    if (!apps) return [];

    return toJS(apps).filter(app => {
      return ~app.name.toLowerCase().indexOf(text);
    });
  }

  render() {
    const { apps, searchText, onSearchTextChange } = this.store;
    const list = this.getApps();

    return (
      <Fragment>
        <SearchBar
          value={searchText}
          placeholder="Search"
          onChange={onSearchTextChange}
        />
        <If condition={!apps}>
          <Then><Loading loading={true} content='正在加载应用列表...' /></Then>
          <Else><AppList list={list} /></Else>
        </If>
      </Fragment>
    );
  }
}